package com.company.aop.service.impl;


import com.company.aop.dao.IAccountDao;
import com.company.aop.pojo.Account;
import com.company.aop.service.IAccountService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @date : 2022/3/25 21:29
 * 服务层实现类
 */

@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    // 数据访问层接口
    private IAccountDao accountDao;

    /**
     * 通过构造方法进行依赖注入
     *
     * @param accountDao
     */
    public AccountServiceImpl(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public boolean saveAccount(Account account) {
        return accountDao.saveAccount(account) > 0;
    }

    @Override
    public Account findById(Integer id) {
        return accountDao.selectById(id);
    }

    @Override
    public List<Account> getAll() {
        return accountDao.getAll();
    }

    @Override
    public boolean updateAccount(Account account) {
        return accountDao.updateAccount(account) > 0;
    }

    @Override
    public boolean deleteAccount(Integer id) {
        return accountDao.deleteAccount(id) > 0;
    }

    @Override
    public boolean transfer(Integer sourceAccountId, Integer targetAccountId, Double money) {
        // 1.根据id查询两个账户信息
        Account sourceAccount = accountDao.selectById(sourceAccountId);
        Account targetAccount = accountDao.selectById(targetAccountId);
        // 2.判断要转出的账户余额是否充足
        if (sourceAccount.getMoney() < money) {
            // 余额不足，转账失败
            return false;
        }
        // 余额足够，继续转账
        sourceAccount.setMoney(sourceAccount.getMoney() - money);
        targetAccount.setMoney(targetAccount.getMoney() + money);

        // 3.将修改的信息写入数据库
        if (accountDao.updateAccount(sourceAccount) == 0) {
            return false;
        }

        // 模拟转账异常
        int i = 1 / 0;

        // 4.将修改的信息写入数据库
        if (accountDao.updateAccount(targetAccount) == 0) {
            return false;
        }
        return true;
    }
}
